package com.ruoyi.jjyh.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.CommonRpc;
import com.ruoyi.common.utils.EmptyUtils;
import com.ruoyi.common.utils.IdWorker;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.jjyh.domain.*;
import com.ruoyi.jjyh.service.*;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;

/**
 * 易货订单Controller
 * 
 * @author ruoyi
 * @date 2020-11-25
 */
@Controller
@RequestMapping("/phone/jjyh/order")
public class JjyhOrderPhoneController extends BaseController
{

    @Autowired
    private IJjyhOrderService jjyhOrderService;
    @Autowired
    private IJjyhOrderGoodsService jjyhOrderGoodsService;

    @Autowired
    private IJjyhGoodsreleaseService jjyhGoodsreleaseService;

    @Autowired
    private IJjyhCarService jjyhCarService;

    @Autowired
    private IJjyhMassageService jjyhMassageService;

    @Autowired
    private IJjyhCourierServicesService jjyhCourierServicesService;

    /**
     * 直接下单
     * @param userId
     * @param otherUserId
     * @param username
     * @param phone
     * @param address
     * @param goodsId
     * @param num
     * @param otherGoodsIds
     * @param otherNums
     * @return
     */
    @RequestMapping("/saveOrder")
    @ResponseBody
    public AjaxResult saveOrder(String userId, String otherUserId, String username, String phone, String address,
                                String goodsId, int num, String otherGoodsIds, int otherNums){
        JjyhGoodsrelease goodsA = jjyhGoodsreleaseService.selectJjyhGoodsreleaseById(goodsId);
        JjyhGoodsrelease goodsB = jjyhGoodsreleaseService.selectJjyhGoodsreleaseById(otherGoodsIds);
        if(goodsA.getStockCount() < num){
            return error("您的商品不足");
        }
        if(goodsB.getStockCount() < otherNums){
            return error("您想要换的商品数量不足");
        }
        if(goodsB.getBeginCount() > otherNums){
            return error("您想要换的商品数量要大于商品起换量");
        }



        JjyhOrder order = new JjyhOrder();
        order.setId(IdWorker.getId());
        order.setUserInid(otherUserId);
        order.setUserOutid(userId);
        order.setOrderNo(IdWorker.getId());
        order.setOrderInname(username);
        order.setOrderInphone(phone);
        order.setOrderInaddress(address);
        order.setOrderInstatus("1");
        order.setOrderOutstatus("0");
        List<JjyhOrderGoods> list = new ArrayList<>();
        JjyhOrderGoods goods1 = new JjyhOrderGoods();
        JjyhOrderGoods goods2 = new JjyhOrderGoods();
        goods1.setCreateTime(new Date());
        goods1.setOrderId(order.getId());
        goods1.setGoodsId(goodsId);
        goods1.setPrice(goodsA.getGoodsPrice());
        goods1.setNum(Long.valueOf(num));
        goods1.setType("2");
        goods1.setUserId(userId);
        list.add(goods1);

        goods2.setCreateTime(new Date());
        goods2.setOrderId(order.getId());
        goods2.setGoodsId(otherGoodsIds);
        goods2.setPrice(goodsB.getGoodsPrice());
        goods2.setNum(Long.valueOf(otherNums));
        goods2.setType("1");
        goods2.setUserId(otherUserId);
        list.add(goods2);
        order.setJjyhOrderGoodsList(list);


        jjyhOrderService.insertJjyhOrder(order);

        JjyhGoodsrelease goodsA1 = new JjyhGoodsrelease();
        goodsA1.setId(goodsId);
        goodsA1.setStockCount(goodsA.getStockCount() - num);
        jjyhGoodsreleaseService.updateJjyhGoodsrelease(goodsA1);

        JjyhMassage massage = new JjyhMassage();
        massage.setId(IdWorker.getId());
        massage.setOrderId(order.getId());
        massage.setUserId(otherUserId);
        massage.setType("2");
        massage.setTitle("订单消息");
        massage.setContent("有人想跟你换货，请尽快查看");
        massage.setClassification("1");
        jjyhMassageService.insertJjyhMassage(massage);

        return success("操作成功", order.getId());
    }


    /**
     * 通过购物车下单
     * @param userId
     * @param otherUserId
     * @param username
     * @param phone
     * @param address
     * @param goodsId
     * @param num
     * @param otherGoodsIds
     * @param otherNums
     * @param carIds
     * @return
     */
    @RequestMapping("/saveCarOrder")
    @ResponseBody
    public AjaxResult saveCarOrder(String userId, String otherUserId, String username, String phone, String address,
                                String goodsId, int num, String otherGoodsIds, String otherNums, String carIds){
        JjyhOrder order = new JjyhOrder();
        order.setId(IdWorker.getId());
        order.setUserInid(otherUserId);
        order.setUserOutid(userId);
        order.setOrderNo(IdWorker.getId());
        order.setOrderOutname(username);
        order.setOrderOutphone(phone);
        order.setOrderOutaddress(address);
        order.setOrderInstatus("1");
        order.setOrderOutstatus("0");
        List<JjyhOrderGoods> list = new ArrayList<>();
        JjyhGoodsrelease goodsA = jjyhGoodsreleaseService.selectJjyhGoodsreleaseById(goodsId);
        if(goodsA.getStockCount() < num){
            return error("您的商品不足");
        }


        String[] _otherGoodsIds = otherGoodsIds.split(",");
        String[] _otherNums = otherNums.split(",");
        for(int i=0;i<_otherGoodsIds.length;i++){
            String otherGoodsId = _otherGoodsIds[i];
            int otherNum = Integer.valueOf(_otherNums[i]);

            JjyhGoodsrelease goodsB = jjyhGoodsreleaseService.selectJjyhGoodsreleaseById(otherGoodsId);

            if(goodsB.getStockCount() < otherNum){
                return error("您想要换的商品数量不足");
            }
            if(goodsB.getBeginCount() > otherNum){
                return error("您想要换的商品数量要大于商品起换量");
            }

            JjyhOrderGoods goods2 = new JjyhOrderGoods();
            goods2.setCreateTime(new Date());
            goods2.setOrderId(order.getId());
            goods2.setGoodsId(otherGoodsId);
            goods2.setPrice(goodsB.getGoodsPrice());
            goods2.setNum(Long.valueOf(otherNum));
            goods2.setType("1");
            goods2.setUserId(otherUserId);
            list.add(goods2);

        }

        JjyhOrderGoods goods1 = new JjyhOrderGoods();

        goods1.setCreateTime(new Date());
        goods1.setOrderId(order.getId());
        goods1.setGoodsId(goodsId);
        goods1.setPrice(goodsA.getGoodsPrice());
        goods1.setNum(Long.valueOf(num));
        goods1.setType("2");
        goods1.setUserId(userId);
        list.add(goods1);

        order.setJjyhOrderGoodsList(list);
        jjyhOrderService.insertJjyhOrder(order);

        JjyhGoodsrelease goodsA1 = new JjyhGoodsrelease();
        goodsA1.setId(goodsId);
        goodsA1.setStockCount(goodsA.getStockCount() - num);
        jjyhGoodsreleaseService.updateJjyhGoodsrelease(goodsA1);

        if(EmptyUtils.isNotEmpty(carIds)){
            jjyhCarService.deleteJjyhCarByIds(carIds);
        }


        JjyhMassage massage = new JjyhMassage();
        massage.setId(IdWorker.getId());
        massage.setOrderId(order.getId());
        massage.setUserId(otherUserId);
        massage.setType("2");
        massage.setTitle("订单消息");
        massage.setContent("有人想跟你换货，请尽快查看");
        massage.setClassification("1");
        jjyhMassageService.insertJjyhMassage(massage);


        return success("操作成功", order.getId());
    }


    /**
     * 取消订单
     * @param userId
     * @param orderId
     * @return
     */
    @RequestMapping("/cancelOrder")
    @ResponseBody
    public AjaxResult cancelOrder(String userId, String orderId){
        JjyhOrder order = jjyhOrderService.selectJjyhOrderById(orderId);
        String userOutId = order.getUserOutid();
        String userInId = order.getUserInid();
        //获取主动方商品信息
        JjyhOrderGoods jjyhOrderGoods = new JjyhOrderGoods();
        jjyhOrderGoods.setOrderId(orderId);
        jjyhOrderGoods.setUserId(userOutId);
        JjyhOrderGoods goods = jjyhOrderGoodsService.selectJjyhOrderGoodsList(jjyhOrderGoods).get(0);
        String goodsId = goods.getGoodsId();
        int num = goods.getNum().intValue();

        //修改订单状态
        JjyhOrder order1 = new JjyhOrder();
        order1.setId(orderId);
        order1.setOrderInstatus("5");
        order1.setOrderOutstatus("5");
        jjyhOrderService.updateJjyhOrder(order1);

        //修改商品数量
        JjyhGoodsrelease goodsA = jjyhGoodsreleaseService.selectJjyhGoodsreleaseById(goodsId);

        JjyhGoodsrelease goodsA1 = new JjyhGoodsrelease();
        goodsA1.setId(goodsId);
        goodsA1.setStockCount(goodsA.getStockCount() + num);
        jjyhGoodsreleaseService.updateJjyhGoodsrelease(goodsA1);


        if(userId.equals(userInId))userId = userOutId;
        if(userId.equals(userOutId))userId = userInId;

        //添加订单消息
        JjyhMassage massage = new JjyhMassage();
        massage.setId(IdWorker.getId());
        massage.setOrderId(order.getId());
        massage.setUserId(userId);
        massage.setType("2");
        massage.setTitle("订单消息");
        massage.setContent("您的订单已被对方取消");
        massage.setClassification("-1");
        jjyhMassageService.insertJjyhMassage(massage);

        return success("操作成功", order.getId());
    }

    /**
     * 获取订单列表
     * @param pageNumber
     * @param pageSize
     * @param userId
     * @param type 状态  0待回复 1待确认 2待发货 3待收货 4已完成 5关闭 6售后/退款  全部此参数空
     * @return
     */
    @RequestMapping("/getOrderList")
    @ResponseBody
    public AjaxResult getGoodsList(int pageNumber, int pageSize,String userId, String type){
        Map<String, Object> map = new HashMap<>();
        map.put("pageNumber", (pageNumber-1) * pageSize);
        map.put("pageSize", pageSize);
        map.put("userId", userId);
        map.put("type", type);

        List<JjyhOrder> orderList = jjyhOrderService.selectOrderList(map);
        for(JjyhOrder a:orderList){
            JjyhOrderGoods jjyhOrderGoods = new JjyhOrderGoods();
            jjyhOrderGoods.setUserId(userId);
            jjyhOrderGoods.setOrderId(a.getId());
            List<JjyhOrderGoods> jjyhOrderGoodsList = jjyhOrderGoodsService.selectOrderGoodsList(jjyhOrderGoods);
            a.setJjyhOrderGoodsList(jjyhOrderGoodsList);
        }

        return success("获取成功", orderList);
    }

    /**
     * 查询订单详情
     * @param userId
     * @param id
     * @return
     */
    @RequestMapping("/getOrderById")
    @ResponseBody
    public AjaxResult getOrderById(String userId, String id){
        Map<String, Object> map = new HashMap<>();
        map.put("userId", userId);
        map.put("id", id);
        List<JjyhOrder> orderList = jjyhOrderService.selectOrderList(map);
        return success("获取成功", orderList.get(0));
    }

    /**
     * 提醒回复
     * @param userId
     * @param orderId
     * @return
     */
    @RequestMapping("/reminderOrder")
    @ResponseBody
    public AjaxResult reminderOrder(String userId, String orderId){
        JjyhOrder jjyhOrder = jjyhOrderService.selectJjyhOrderById(orderId);
        String userInId = jjyhOrder.getUserInid();
        String userOutId = jjyhOrder.getUserOutid();
        if(userId.equals(userInId))userId = userOutId;
        if(userId.equals(userOutId))userId = userInId;

//        JjyhMassage massage = new JjyhMassage();
//        massage.setOrderId(orderId);
//        massage.setUserId(userId);
//        massage.setClassification("2");
//        List<JjyhMassage> list = jjyhMassageService.selectJjyhMassageList(massage);
//        if(list.size() > 0){
//            return error("请勿重复提醒");
////            return success("提醒成功");
//        }

        JjyhMassage massage = new JjyhMassage();
        massage.setId(IdWorker.getId());
        massage.setOrderId(orderId);
        massage.setUserId(userId);
        massage.setType("2");
        massage.setTitle("订单消息");
        massage.setContent("您有新的换货申请，请及时查看");
        massage.setClassification("2");
        jjyhMassageService.insertJjyhMassage(massage);
        return success("提醒成功");
    }

    /**
     * 确认订单 -- 设置保证金金额 -- 收获地址
     * @param orderId
     * @param userId
     * @return
     */
    @RequestMapping("/confirmOrder")
    @ResponseBody
    public AjaxResult confirmOrder(String orderId, String userId, String money, String username, String phone, String address){
        JjyhOrder jjyhOrder = jjyhOrderService.selectJjyhOrderById(orderId);
        JjyhOrder jjyhOrder1 = new JjyhOrder();
        jjyhOrder1.setId(orderId);
        jjyhOrder1.setOrderInstatus("2");
        jjyhOrder1.setOrderOutstatus("2");


        jjyhOrder1.setChangeOutstatus("1");
        jjyhOrder1.setChangeInstatus("1");


        jjyhOrder1.setSecurityInmoney(new BigDecimal(money));
        jjyhOrder1.setSecurityOutmoney(jjyhOrder1.getSecurityInmoney());
        jjyhOrder1.setOrderInaddress(address);
        jjyhOrder1.setOrderInphone(phone);
        jjyhOrder1.setOrderInname(username);

        jjyhOrderService.updateJjyhOrder(jjyhOrder1);

        String userInId = jjyhOrder.getUserInid();
        String userOutId = jjyhOrder.getUserOutid();
        if(userId.equals(userInId))userId = userOutId;
        if(userId.equals(userOutId))userId = userInId;

        JjyhMassage massage = new JjyhMassage();
        massage.setId(IdWorker.getId());
        massage.setOrderId(orderId);
        massage.setUserId(userId);
        massage.setType("2");
        massage.setTitle("订单消息");
        massage.setContent("对方已确定与您换货，请尽快确认保证金");
        massage.setClassification("3");
        jjyhMassageService.insertJjyhMassage(massage);
        return success("操作成功");
    }


    /**
     * 确认保证金金额
     * @param orderId
     * @param userId
     * @return
     */
    @RequestMapping("/confirmBond")
    @ResponseBody
    public AjaxResult confirmBond(String orderId, String userId){
        JjyhOrder jjyhOrder = jjyhOrderService.selectJjyhOrderById(orderId);

        JjyhOrder jjyhOrder1 = new JjyhOrder();
        jjyhOrder1.setId(orderId);
        jjyhOrder1.setChangeOutstatus("1");
        jjyhOrder1.setChangeInstatus("1");

        jjyhOrderService.updateJjyhOrder(jjyhOrder1);

        String userInId = jjyhOrder.getUserInid();
        String userOutId = jjyhOrder.getUserOutid();
        if(userId.equals(userInId))userId = userOutId;
        if(userId.equals(userOutId))userId = userInId;

        JjyhMassage massage = new JjyhMassage();
        massage.setId(IdWorker.getId());
        massage.setOrderId(orderId);
        massage.setUserId(userId);
        massage.setType("2");
        massage.setTitle("订单消息");
        massage.setContent("对方已确认保证金金额，请支付保证金");
        massage.setClassification("5");
        jjyhMassageService.insertJjyhMassage(massage);
        return success("操作成功");
    }


    /**
     * 获取物流公司
     * @return
     */
    @RequestMapping("/getCourierServices")
    @ResponseBody
    public AjaxResult getCourierServices(){
        List<JjyhCourierServices> list = jjyhCourierServicesService.selectJjyhCourierServicesList(new JjyhCourierServices());
        return success("获取成功", list);
    }


    /**
     * 填写物流信息
     * @param orderId
     * @param userId
     * @param trackno
     * @param trackname
     * @param tracknameCode
     * @return
     */
    @RequestMapping("/saveCourier")
    @ResponseBody
    public AjaxResult saveCourier(String orderId, String userId, String trackno, String trackname, String tracknameCode){
        JjyhOrder jjyhOrder = jjyhOrderService.selectJjyhOrderById(orderId);

        String type = "";


        String userInId = jjyhOrder.getUserInid();
        String userOutId = jjyhOrder.getUserOutid();
        if(userId.equals(userInId))type = "in";
        if(userId.equals(userOutId))type = "out";
        JjyhOrder jjyhOrder1 = new JjyhOrder();
        jjyhOrder1.setId(orderId);
        if("in".equals(type)){
            jjyhOrder1.setChangeIntrackno(trackno);
            jjyhOrder1.setChangeIntrackname(trackname);
            jjyhOrder1.setChangeIntracknamecode(tracknameCode);
            if(EmptyUtils.isNotEmpty(jjyhOrder.getChangeOuttrackno())){
                jjyhOrder1.setOrderInstatus("3");
                jjyhOrder1.setOrderOutstatus("3");
            }
        }
        if("out".equals(type)){
            jjyhOrder1.setChangeOuttrackno(trackno);
            jjyhOrder1.setChangeOuttrackname(trackname);
            jjyhOrder1.setChangeOuttracknamecode(tracknameCode);
            if(EmptyUtils.isNotEmpty(jjyhOrder.getChangeIntrackno())){
                jjyhOrder1.setOrderInstatus("3");
                jjyhOrder1.setOrderOutstatus("3");
            }
        }

        jjyhOrderService.updateJjyhOrder(jjyhOrder1);



        JjyhMassage massage = new JjyhMassage();
        massage.setId(IdWorker.getId());
        massage.setOrderId(orderId);
        massage.setUserId(userId);
        massage.setType("2");
        massage.setTitle("订单消息");
        massage.setContent("对方已发货，请注意物流信息");
        massage.setClassification("7");
        jjyhMassageService.insertJjyhMassage(massage);
        return success("操作成功");
    }

    /**
     * 删除订单
     * @param userId
     * @param orderId
     * @return
     */
    @RequestMapping("/delOrder")
    @ResponseBody
    public AjaxResult delOrder(String userId, String orderId){
        JjyhOrder jjyhOrder = jjyhOrderService.selectJjyhOrderById(orderId);
        JjyhOrder jjyhOrder1 = new JjyhOrder();
        jjyhOrder1.setId(orderId);
        jjyhOrder1.setDeluserids(jjyhOrder.getDeluserids() + "," + userId);
        jjyhOrderService.updateJjyhOrder(jjyhOrder1);
        return success("删除成功");
    }


    /**
     * 确认收货
     * @param orderId
     * @param userId
     * @return
     */
    @RequestMapping("/subCourier")
    @ResponseBody
    public AjaxResult subCourier(String orderId, String userId){
        JjyhOrder jjyhOrder = jjyhOrderService.selectJjyhOrderById(orderId);

        String type = "";
        String userInId = jjyhOrder.getUserInid();
        String userOutId = jjyhOrder.getUserOutid();
        if(userId.equals(userInId))type = "in";
        if(userId.equals(userOutId))type = "out";

        JjyhOrder jjyhOrder1 = new JjyhOrder();
        jjyhOrder1.setId(orderId);
        if("in".equals(type)){
            jjyhOrder1.setOrderInstatus("6");
            if("6".equals(jjyhOrder.getOrderOutstatus())){
                jjyhOrder1.setOrderInstatus("4");
                jjyhOrder1.setOrderOutstatus("4");
            }
        }
        if("out".equals(type)){
            jjyhOrder1.setOrderOutstatus("6");
            if("6".equals(jjyhOrder.getOrderInstatus())){
                jjyhOrder1.setOrderInstatus("4");
                jjyhOrder1.setOrderOutstatus("4");
            }
        }
        jjyhOrderService.updateJjyhOrder(jjyhOrder1);

        JjyhMassage massage = new JjyhMassage();
        massage.setId(IdWorker.getId());
        massage.setOrderId(orderId);
        massage.setUserId(userId);
        massage.setType("2");
        massage.setTitle("订单消息");
        massage.setContent("对方已确认收获");
        massage.setClassification("8");
        jjyhMassageService.insertJjyhMassage(massage);
        return success("操作成功");
    }

    /**
     * 获取物流信息
     * @param com
     * @param no
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getLogisticsInformation")
    @ResponseBody
    public AjaxResult getLogisticsInformation(String com, String no)throws Exception{
        String result = null;
        try {
            CloseableHttpClient client = null;
            CloseableHttpResponse response = null;
            try {
                HttpGet httpGet = new HttpGet("http://v.juhe.cn/exp/index?com="+com+"&no="+no+"&key=9a4090e5886ecd9fe24c1926053d315a");

                client = HttpClients.createDefault();
                response = client.execute(httpGet);
                HttpEntity entity = response.getEntity();
                result = EntityUtils.toString(entity);
                System.out.println(result);
            } finally {
                if (response != null) {
                    response.close();
                }
                if (client != null) {
                    client.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return success("操作成功", JSON.parseObject(result, new TypeReference<Map<String, Object>>(){}));
    }

}
